﻿namespace UnityEngine
{
	public static class RectTransformExt
	{

		static readonly Vector3[] m_WorldCorners = new Vector3[4];
		static readonly Vector3[] m_CanvasCorners = new Vector3[4];
		/// <summary>
		/// convert local rect to world rect
		/// </summary>
		/// <param name="self"></param>
		/// <param name="rect">local rect</param>
		/// <returns></returns>
		public static Rect ToWorldRect(this Transform self,Rect rect)
		{
			var min = self.TransformPoint(rect.min);
			var max = self.TransformPoint(rect.max);
			rect.min = min;
			rect.max = max;
			return rect;
		}

		public static Rect GetCanvasRect(this RectTransform self,Canvas canvas)
		{
			var c = canvas;
			var t = self;

			if (c == null)
				return new Rect();

			t.GetWorldCorners(m_WorldCorners);
			var canvasTransform = c.GetComponent<Transform>();
			for (int i = 0; i < 4; ++i)
			{
				m_CanvasCorners[i] = canvasTransform.InverseTransformPoint(m_WorldCorners[i]);
			}

			return new Rect(m_CanvasCorners[0].x, m_CanvasCorners[0].y, m_CanvasCorners[2].x - m_CanvasCorners[0].x, m_CanvasCorners[2].y - m_CanvasCorners[0].y);
		}
		public static Rect GetWorldRect(this RectTransform self)
		{
			var rect = self.rect;
			rect = self.ToWorldRect(rect);
			return rect;
		}

	}
}